<template>
  <div>
    <div class="left-container">
      <el-card class="card-body">
          <div slot="header"><span>模型设置</span></div>
          <el-row :gutter="20">
            <el-col>
              <el-form size="small" :inline="true" label-width="90px">
                <el-form-item label="已有模型">
                  <el-select v-model="siloConfId" placeholder="请选择" clearable filterable @change="initAlrModel()">
                    <el-option
                      v-for="item in siloConfList"
                      :key="item.siloConfId"
                      :label="item.siloConfName"
                      :value="item.siloConfId">
                      <span>{{item.siloConfName}}</span>
                      <span class="el-icon-close" @click.stop="removeOption(item)"></span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="模型添加">
                  <el-select v-model="modelType" placeholder="请选择" @change="changeInitModel()">
                    <el-option
                      v-for="dict in dict.type.sys_init_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-for="(item,index) in paramLabel" :key="index" :label="'设置'+item">
                  <el-input class="svgInput" :placeholder="'请输入'+paramLabel" @input="thisRegex(index)" v-model="paramValue[index]" ></el-input>
                </el-form-item>
                <el-form-item v-if="paramLabel.length" label="左右移动(x)">
                  <el-input class="svgInput" placeholder="右为正,左为负" @input="thisRegex(paramLabel.length)" v-model="paramValue[paramLabel.length]" ></el-input>
                </el-form-item>
                <el-form-item v-if="paramLabel.length" label="前后移动(y)">
                  <el-input class="svgInput" placeholder="前为正,后为负" @input="thisRegex(paramLabel.length+1)" v-model="paramValue[paramLabel.length+1]" ></el-input>
                </el-form-item>
                <el-form-item v-if="paramLabel.length" label="上下移动(y)">
                  <el-input class="svgInput" placeholder="上为正,下为负" @input="thisRegex(paramLabel.length+2)" v-model="paramValue[paramLabel.length+2]" ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    plain
                    size="mini"
                    @click="addModel()"
                  >添加</el-button>
                  <el-button
                  type="success"
                  plain
                  size="mini"
                  @click="editModel()"
                >修改</el-button>
                  <el-button
                    type="success"
                    plain
                    size="mini"
                    @click="deleteModel()"
                  >删除</el-button>
                  <el-button
                    type="primary"
                    plain
                    size="mini"
                    @click="saveSilo()"
                  >保存</el-button>
                  <el-button
                    type="danger"
                    plain
                    size="mini"
                    @click="clearModel()"
                  >清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
      </el-card>
    </div>
    <div class="mid-container">
      <div v-if="this.series.length > 0" class="model-select">
        <el-select v-model="thisModelIndex" placeholder="请选择" @change="changeModel()">
          <el-option
            v-for="(item,index) in legend"
            :key="index"
            :label="item"
            :value="index">
          </el-option>
        </el-select>
      </div>
      <div ref="modelChart" class="chart-container"></div>
    </div>
    <el-dialog title="模型名称添加" :visible.sync="saveOpen" width="600px" append-to-body>
      <el-form ref="siloConfName" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="料仓名称" prop="siloConfName">
              <el-input v-model="siloConfName" placeholder="请输入料仓名称" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" v-if="siloConfId" @click="updateModel">修 改</el-button>
        <el-button type="primary" v-if="siloConfId" @click="submitModel">新 增</el-button>
        <el-button type="primary" v-if="!siloConfId" @click="submitModel">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import * as echarts from "echarts";
import 'echarts-gl';
import allModel from '@/views/radarSilo/initModel/allModel';
import initModelMethod from '@/views/radarSilo/initModel/initModelMethod';

import {selectSiloConfList,addSiloConf,updateSiloConf,deleteSiloConf} from '@/api/radar/radarSiloConf';
// import { addSilo } from "../../../api/radar/radarSilo";

export default {
  dicts: ['sys_init_model'],
  data(){
    return{
      modelType:"1",         //模型默认第一个
      paramLabel:[],         //字典中remark分段，代表模型属性
      paramValue:undefined,  //参数数组
      modelWatch:undefined,  //监视字典 
      initModel:undefined,   //初始模型转换为可使用类型
      siloChart:null,
      series:[],
      compareMax:[],
      maxMins:[],
      legend:[],
      option:undefined,
      thisModelIndex:undefined,
      allParamValue:[],
      allModelType:[],
      siloConfName:"",
      siloConfList:[],   //所有已经建立的料仓模型
      siloConfId:undefined,//所选择的已有模型的id
      siloConfindex:undefined,
      saveOpen:false,
      // thisRegex:
      rules: {
        siloConfName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" },
          { min: 0, max: 20, message: '设备名称长度必须介于 0 和 20 之间', trigger: 'blur' }
        ],
      }
    }
  },
  watch:{
    modelWatch: {
      handler(newValue) {
        this.initModel = JSON.parse(JSON.stringify(this.modelWatch))
        if(!this.initModel[0]) return
        this.changeInitModel();
      },
      deep:true,
    },
    // modelType:{
    //   handler(newValue) {
    //     this.changeInitModel();
    //   }
    // }

  },
  mounted(){
    this.modelWatch = this.dict.type.sys_init_model
    this.getSiloConfList();
    window.onresize = () => {
      return (() => {
          this.chartResize()
      })()
    }
  },
  beforeDestroy(){
    if(this.siloChart){
      this.siloChart.dispose();
      this.siloChart = null;
    }
  },
  methods:{
    //初始化已有模型，若选择
    getSiloConfList(){
      selectSiloConfList({type:"1"}).then(res =>{
        this.siloConfList = res.data.data;
        // console.log("111111111",this.siloConfList)
      })
    },
    initAlrModel(){
      if(!this.siloConfId){
        this.siloConfindex = undefined
        this.siloConfId = undefined
        return;
      } 
      this.siloConfindex = this.siloConfList.findIndex((item) => item.siloConfId == this.siloConfId);
      var siloConf = this.siloConfList[this.siloConfindex];
      var object = initModelMethod.initConfModel(siloConf);
      this.series = object.series;
      this.maxMins = object.realMaxMins;
      this.legend = object.legend;
      this.thisModelIndex = this.series.length-1;
      this.allModelType = JSON.parse(siloConf.siloInitId);
      this.modelType = this.allModelType[this.thisModelIndex];
      this.changeInitModel();
      this.allParamValue = JSON.parse(siloConf.siloParam);
      this.paramValue = JSON.parse(JSON.stringify(this.allParamValue[this.thisModelIndex]));
      this.updateChart();
    },

    //初始化模型
    changeInitModel(type){
      var remark = this.initModel[this.modelType-1].raw.remark
      if(!remark) return;
      this.paramLabel = remark.split(",")
      if(type != "change"){
        this.compareMax[0] = [];
        this.compareMax[1] = [];
        this.compareMax[2] = [];
        this.compareMax[3] = [];
        this.paramValue = [];
      // if(this.thisModelIndex === undefined)

        for(var i = 0;i < (this.paramLabel.length+3);i++){
          var length = this.paramLabel.length;
          if(this.modelType == "4"||this.modelType=="5"||this.modelType=="6") length = length-4;
          if(i < length){
            this.paramValue.push(1)
          }else{
            this.paramValue.push(0)
          };
        }
      }
      // }
    },
    changeModel(){
      if(this.thisModelIndex !== undefined){
        this.paramValue = this.allParamValue[this.thisModelIndex]
        this.modelType = this.allModelType[this.thisModelIndex]
        this.changeInitModel("change");
      }
      this.updateChart();
    },
    chooseModelInit(){
      var object = undefined;
      if(this.modelType == "1"){
        object = allModel.circleBarModel(this.paramValue,this.thisModelIndex);
      }else if(this.modelType == "2"){
        object = allModel.archHorModel(this.paramValue,this.thisModelIndex);
      }else if(this.modelType == "3"){
        object = allModel.archLonModel(this.paramValue,this.thisModelIndex);
      }else if(this.modelType == "4"){
        object = allModel.planeModel(this.paramValue,this.thisModelIndex);
      }else if(this.modelType == "5"){
        object = allModel.planeHorModel(this.paramValue,this.thisModelIndex);
      }else if(this.modelType == "6"){
        object = allModel.planeLonModel(this.paramValue,this.thisModelIndex);
      }
      return object;
    },
    addModel(){
      this.paramToNumber();
      this.thisModelIndex = this.series.length;
      // console.log("???????????")
      var object = this.chooseModelInit();
      var series = object.series;
      this.compareMaxMin(object);
      this.series.push(series);
      this.legend[this.thisModelIndex] = this.thisModelIndex+1+"号模型"
      this.allModelType[this.thisModelIndex] = this.modelType;
      // this.allParamValue[this.thisModelIndex] = [];
      this.allParamValue.push(JSON.parse(JSON.stringify(this.paramValue)))
      this.updateChart();
      
    },
    compareMaxMin(object){
      if(this.compareMax){
        this.compareMax[0][this.thisModelIndex] = object.realMaxMin[0]
        this.compareMax[1][this.thisModelIndex] = object.realMaxMin[1]
        this.compareMax[2][this.thisModelIndex] = object.realMaxMin[2]
        this.compareMax[3][this.thisModelIndex] = object.realMaxMin[3]
      }
      this.maxMins[0] = Math.min(...this.compareMax[0])
      this.maxMins[1] = Math.max(...this.compareMax[1])
      this.maxMins[2] = Math.min(...this.compareMax[2])
      this.maxMins[3] = Math.max(...this.compareMax[3])
    },
    editModel(){
      if(this.thisModelIndex === undefined) return this.$message.error("您还没有创建模型");
      this.paramToNumber();
      var object = this.chooseModelInit();
      var series = object.series;
      this.compareMaxMin(object);
      this.series[this.thisModelIndex] = series;
      this.allParamValue[this.thisModelIndex] = JSON.parse(JSON.stringify(this.paramValue))
      this.allModelType[this.thisModelIndex]
      this.updateChart();
    },
    deleteModel(){
      if(this.thisModelIndex === undefined) return this.$message.error("您还没有创建模型");
      this.$modal.confirm('您确认要删除'+this.legend[this.thisModelIndex]+'吗？').then(function() {
        return;
      }).then(() => {
        var changeIndex = false;
        if(this.thisModelIndex+1 < this.series.length) changeIndex = true;
        this.series.splice(this.thisModelIndex,1);
        this.legend.splice(this.thisModelIndex,1);
        this.allModelType.splice(this.thisModelIndex,1);
        this.allParamValue.splice(this.thisModelIndex,1);
        if(changeIndex){
          this.series.forEach((item,index)=>{
            if(index >= this.thisModelIndex){
              item.name = index+1+"号模型"
              item.grid3DIndex = index
              this.legend[index] = item.name
            };
          })
        }

        if(this.series.length === 0){
          this.thisModelIndex = undefined;
        }else{
          this.thisModelIndex = this.series.length - 1;
          this.modelType = this.allModelType[this.thisModelIndex]
        }
        this.changeInitModel();
        this.updateChart();
        if(this.thisModelIndex !== undefined){
          this.paramValue = this.allParamValue[this.thisModelIndex]
        }
      })
    },
    saveSilo(){
      if(this.thisModelIndex == undefined) return this.$message.error("您还没有创建模型");
      this.saveOpen = true;
      if(this.siloConfId) this.siloConfName = this.siloConfList[this.siloConfindex].siloConfName
    },
    updateModel(){
      if(!this.siloConfName || this.siloConfName.length > 20) return this.$message.error("模型名称不能为空");
      updateSiloConf({siloConfId:this.siloConfId,siloInitId:JSON.stringify(this.allModelType),siloParam:JSON.stringify(this.allParamValue),siloConfName:this.siloConfName}).then(res=>{
        this.$modal.msgSuccess("修改成功");
        this.getSiloConfList();
        
        if(this.siloConfId){
          this.siloConfindex = this.siloConfList.findIndex((item) => item.siloConfId == this.siloConfId);
        } 
      });
      this.saveOpen = false;
    },
    submitModel(){
      if(!this.siloConfName || this.siloConfName.length > 20) return this.$message.error("模型名称不能为空");
      addSiloConf({siloInitId:JSON.stringify(this.allModelType),siloParam:JSON.stringify(this.allParamValue),siloConfName:this.siloConfName}).then(res=>{
        this.$modal.msgSuccess("新增成功");
        this.getSiloConfList();
        if(this.siloConfId){
          this.siloConfindex = this.siloConfList.findIndex((item) => item.siloConfId == this.siloConfId);
        } 
      });
      this.saveOpen = false;
    },
    cancel(){
      this.saveOpen = false;
    },
    clearModel(){
      if(!this.siloChart) return this.$message.error("您还没有创建模型");
      this.$modal.confirm('您确认要清空当前所有模型吗？').then(function() {
        return;
      }).then(() => {
        this.series = [];
        this.legend = [];
        this.allModelType = [];
        this.allParamValue = [];
        this.thisModelIndex = undefined;
        this.updateChart();
      })
    },
    updateChart(){
      // if(!this.siloChart) return;
      if(this.siloChart){
        this.option.series = this.series;
        this.option.legend.data = this.legend;
        this.editMax();
        this.option.visualMap[1].seriesIndex = this.thisModelIndex
      }else{
        this.option = {
          tooltip: {
            show:false,
          },
          legend:{
            right:'1%',
            top:'10',
            data:this.legend,
            textStyle:{
              color:'#fff'
            }
          },
          visualMap: [{
            show: false,
            inRange: {
              color: [
                'rgba(255,255,255,0.6)'
              ]
            }
          },{
            show: false,
            seriesIndex:this.thisModelIndex,
            inRange: {
              color: [
                'rgba(0,191,255,0.4)'
              ]
            }
          }],
          xAxis3D: {
              // axisPointer: { show: false }
              min:this.maxMins[0],
              max:this.maxMins[1],
              nameTextStyle:{
                color:'#fff'
              },
              axisLine:{
                lineStyle:{
                  color:'#fff'
                },
              },
              axisLabel:{
                textStyle:{
                  color:'#fff'
                }
              },
            },
            yAxis3D: {
              // axisPointer: { show: false }
              min:this.maxMins[2],
              max:this.maxMins[3],
              nameTextStyle:{
                color:'#fff'
              },
              axisLine:{
                lineStyle:{
                  color:'#fff'
                },
              },
              axisLabel:{
                textStyle:{
                  color:'#fff'
                }
              },
            },
          zAxis3D: {
            nameTextStyle:{
              color:'#fff'
            },
            axisLine:{
              lineStyle:{
                color:'#fff'
              },
            },
            axisLabel:{
              textStyle:{
                color:'#fff'
              }
            },
          },
          grid3D: {},
          series: this.series
        };
        this.siloChart = echarts.init(this.$refs.modelChart);
      }
      this.siloChart.setOption(this.option,true);
    },
    editMax(){
      this.option.xAxis3D.min = this.maxMins[0]
      this.option.xAxis3D.max = this.maxMins[1]
      this.option.yAxis3D.min = this.maxMins[2]
      this.option.yAxis3D.max = this.maxMins[3]
    },
    removeOption(siloConf){
      this.$modal.confirm('是否确认删除名称为"' + siloConf.siloConfName + '"的数据项？').then(function() {
        return deleteSiloConf(siloConf.siloConfId);
      }).then(() => {
        this.getSiloConfList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    paramToNumber(){
      this.paramValue.forEach((item,index)=>{
        if(item === '-') this.paramValue[index] = 0;
        if(typeof(this.paramValue[index]) == "string"){
          this.paramValue[index] = Number(item.replace(/^(\d+)\.$/,'$1'))
        };
      })
    },
    chartResize(){
      if(this.siloChart){
        this.siloChart.resize();
      }
    },
    thisRegex(index){
      // this.paramValue[index] = '1'
      var regex = /[^0-9.]|(?<=\..*)\.|(?<!\d)\.|(?!^)-/g;
      var length = this.paramLabel.length;
      if(this.modelType == "4"||this.modelType=="5"||this.modelType=="6") length = length-4;
      if(index >= length) regex = /[^0-9.-]|(?<=\..*)\.|(?<!\d)\.|(?!^)-/g;// 只允许数字和点和负号
      this.paramValue[index] = this.paramValue[index]
      .replace(regex, '') // 只允许数字和点
      .replace(/^0+([1-9])/, '$1') // 排除开头为0的情况，除非是0本身
      .replace(/^(\d*)\./, '$1.') // 保证第一位是数字，可以是0
      .replace(/^(\-?)\-*0+(\d*)$/, '$1$2')// 移除开头多余的零

      if(this.modelType == '1'&&(index == 0 || index == 1)){
        var max = this.paramValue[0] > this.paramValue[1]?this.paramValue[0] : this.paramValue[1];
        this.paramValue[2] = max;
        this.paramValue[3] = max;
      }

      if (this.paramValue[index].length === 0) {
        this.paramValue[index] = 0;
      }
    }
  }

}
</script>

<style scoped>
.left-container{
  position: absolute;
  width: 30%;
  height: 100%;
  left: 2%;
}
.mid-container{
  position: absolute;
  width: 68%;
  height: 100%;
  left: 32%;
}
.chart-container{
  width: 100%;
  height: 100%;
}
.card-body{
  width: 100%;
  height: calc(100% - 10px);;
  /* background-color: rgba(230, 255, 255, 1); */
}
.model-select{
  position:absolute;
  right: 1%;
  top:35px;
  z-index: 10;
}
::v-deep .el-dialog__body {
  padding: 20px 20px 0px;
}
::v-deep .el-card__body{
  overflow: auto;
  height: 100%;
}
.dialog-footer{
  text-align: center;
}
.el-icon-close{
  float: right;
  line-height: 34px;
  font-weight: bold;
}
.el-icon-close:hover{
  color: 	#4169E1;
}
</style>
